package com.zgw.fireline.design.edit;

import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.rowset.CachedRowSet;

import org.eclipse.debug.internal.ui.DebugUIPlugin;
import org.eclipse.jdt.core.dom.Expression;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.source.IVerticalRuler;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.TableCursor;
import org.eclipse.swt.custom.TableEditor;
import org.eclipse.swt.events.ControlAdapter;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.RowLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Dialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Group;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.swt.widgets.Text;
import org.eclipse.wb.core.model.JavaInfo;
import org.eclipse.wb.internal.core.DesignerPlugin;
import org.eclipse.wb.internal.core.model.JavaInfoEvaluationHelper;
import org.eclipse.wb.internal.core.model.util.ObjectsLabelProvider;
import org.eclipse.wb.internal.core.utils.ast.AstNodeUtils;
import org.eclipse.wb.internal.core.utils.jdt.ui.JdtUiUtils;
import org.eclipse.wb.internal.core.utils.reflect.ReflectionUtils;
import org.eclipse.wb.internal.core.utils.state.GlobalState;
import org.eclipse.wb.internal.core.utils.ui.GridDataFactory;
import org.eclipse.wb.internal.core.utils.ui.GridLayoutFactory;

import syntaxcolor.v4.syntaxcolor.CodeStyleText;

import com.ibm.icu.util.Calendar;
import com.zgw.fireline.design.Activator;
import com.zgw.fireline.design.Model.DatasetInfo;
import com.zgw.fireline.design.Model.IDataBaseProvideHelp;
import com.zgw.fireline.design.common.CodeStyleFactory;
import com.zgw.fireline.design.common.ControlUtil;
import com.zgw.fireline.design.common.ExecutionUtils2;
import org.eclipse.wb.swt.SWTResourceManager;
import org.eclipse.swt.events.MenuAdapter;
import org.eclipse.swt.events.MenuEvent;

/**
 * 数据源管理对话框
 * */
public class DataSourceDialog extends Dialog {

	public static final int OK = 1;
	public static final int CANCEL = 0;
	protected int result;
	protected Shell shell;
	private Table tableParam;
	private Table tableDataColumn;
	private Text textDefineKey; // 数据源编号

	private Combo combSourceProvide;// 数据源提供器
	private CodeStyleText textSql;
	private Text textParamEdit; // 参数编辑 Text
	private TableEditor paramEditor;// 参数编辑器
	private Button btnCustom;
	private Button btnSys;
	private TabFolder tabFolder;
	private final DatasetInfo dataset;
	private Button btnLoadType0, btnLoadType1, btnLoadType2, btnLoadType3;
	private SelectionAdapter checkEnable;
	private Object sysdefine;

	// =======================================
	// 外部引用数据
	// ========================================
	public Class<?> baseProvideClass;
	public String sqlCommand;
	public String defineKey; // 系统资源声明编号
	public boolean isSysSource;
	public Map<Integer, Object> params = new HashMap<Integer, Object>();// 参数信息
	public List<String> keyList = new ArrayList<String>();
	// 0 不加载 1 外部填充 2创建界面之前加载 2 创建界面之后加载
	public int loadType = 0;

	/**
	 * Create the dialog.
	 * 
	 * @param parent
	 * @param style
	 */
	public DataSourceDialog(Shell parent, int style, DatasetInfo datset) {
		super(parent, style);
		setText("SWT Dialog");
		this.dataset = datset;
	}

	/**
	 * Open the dialog.
	 * 
	 * @return the result
	 */
	public int open() {
		createContents();
		Display display = getParent().getDisplay();
		ControlUtil.centerShell(display, shell);
		shell.open();
		shell.layout();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch()) {
				display.sleep();
			}
		}
		return result;
	}

	/**
	 * Create contents of the dialog.
	 */
	private void createContents() {
		shell = new Shell(getParent(), SWT.DIALOG_TRIM | SWT.MAX | SWT.RESIZE);
		shell.setSize(573, 530);
		shell.setText("数据源管理");
		GridLayout gl_shell = new GridLayout(1, false);
		gl_shell.verticalSpacing = 10;
		shell.setLayout(gl_shell);

		tabFolder = new TabFolder(shell, SWT.NONE);
		tabFolder.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1,
				1));
		TabItem tbtmNewItem = new TabItem(tabFolder, SWT.NONE);
		tbtmNewItem.setText("基本信息");

		Composite composite = new Composite(tabFolder, SWT.NONE);
		tbtmNewItem.setControl(composite);
		GridLayout gl_composite = new GridLayout(1, false);
		gl_composite.verticalSpacing = 10;
		gl_composite.marginHeight = 10;
		composite.setLayout(gl_composite);

		Group group = new Group(composite, SWT.NONE);
		group.setLayout(new GridLayout(3, false));
		group.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1,
				1));
		group.setText("解析执行器");

		CLabel lblNewLabel = new CLabel(group, SWT.NONE);
		lblNewLabel.setText("Class:");

		combSourceProvide = new Combo(group, SWT.READ_ONLY);
		combSourceProvide.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (!combSourceProvide.getText().equals("")) {
					try {
						baseProvideClass = IDataBaseProvideHelp
								.loadProvideClass(combSourceProvide.getText());
					} catch (Exception e1) {
						ExecutionUtils2.openErrorDialog("解析器加载失败", e1);
					}
				}
			}
		});
		combSourceProvide.setLayoutData(new GridData(SWT.FILL, SWT.CENTER,
				true, false, 1, 1));

		Menu menu_1 = new Menu(combSourceProvide);
		combSourceProvide.setMenu(menu_1);

		final MenuItem mntmNewItem_3 = new MenuItem(menu_1, SWT.CHECK);
		mntmNewItem_3.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (!combSourceProvide.getText().equals("")) {
					try {
						IDataBaseProvideHelp
								.setDefaultProvideClass(combSourceProvide
										.getText());
					} catch (Exception e1) {
						ExecutionUtils2.openErrorDialog("默认项设置失败", e1);
					}
				}

			}
		});
		mntmNewItem_3.setText("设置当前项为默认项");

		MenuItem mntmNewItem_2 = new MenuItem(menu_1, SWT.NONE);
		mntmNewItem_2.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (!combSourceProvide.getText().equals("")) {
					IDataBaseProvideHelp.unloadProvideClass(combSourceProvide
							.getText());
					combSourceProvide.remove(combSourceProvide.getText());
					baseProvideClass = null;
				}
			}
		});
		mntmNewItem_2.setText("删除当前项");
		mntmNewItem_2.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				IDataBaseProvideHelp.unloadProvideClass(baseProvideClass);
			}
		});
		Button btnNewButton_1 = new Button(group, SWT.NONE);
		btnNewButton_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				doSearchSourceProvide();
			}
		});
		btnNewButton_1.setText("  &S查找...");

		Group group_3 = new Group(composite, SWT.NONE);
		group_3.setText("类别：");
		group_3.setLayout(new GridLayout(4, false));
		group_3.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false,
				1, 1));

		btnCustom = new Button(group_3, SWT.RADIO);
		btnCustom.setText("自定义");

		btnSys = new Button(group_3, SWT.RADIO);
		btnSys.setText("系统定义");

		textDefineKey = new Text(group_3, SWT.BORDER);
		textDefineKey.setToolTipText("系统数据源编号");
		textDefineKey.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true,
				false, 1, 1));

		final Button btnNewButton_11 = new Button(group_3, SWT.NONE);
		btnNewButton_11.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				doSelectedDefine();
			}
		});
		btnNewButton_11.setText("选择... ");
		checkEnable = new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				textDefineKey.setEnabled(btnSys.getSelection());
				textDefineKey.setEditable(false);
				btnNewButton_11.setEnabled(btnSys.getSelection());
				textSql.setEditable(!btnSys.getSelection());
				btnNewButton_11.setFocus();
				if (btnSys.getSelection()) {
					setDefineText();
				} else {
					textSql.setText(sqlCommand == null ? "" : sqlCommand);
				}
			}
		};
		Group group_1 = new Group(composite, SWT.NONE);
		group_1.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, false, false,
				1, 1));

		group_1.setText("加载方式");
		RowLayout rl_group_1 = new RowLayout(SWT.HORIZONTAL);
		rl_group_1.marginTop = 5;
		group_1.setLayout(rl_group_1);

		btnLoadType0 = new Button(group_1, SWT.RADIO);
		btnLoadType0.setSelection(true);
		btnLoadType0.setText("不加载");
		btnLoadType1 = new Button(group_1, SWT.RADIO);
		btnLoadType1.setText("外部填充");

		btnLoadType2 = new Button(group_1, SWT.RADIO);
		btnLoadType2.setText("界面创建之前加载");

		btnLoadType3 = new Button(group_1, SWT.RADIO);
		btnLoadType3.setText("界面创建之后加载");
		Group grpSql = new Group(composite, SWT.NONE);

		grpSql.setText("查询参数、语句");
		FillLayout fl_grpSql = new FillLayout(SWT.HORIZONTAL);
		fl_grpSql.marginHeight = 6;
		grpSql.setLayout(fl_grpSql);
		grpSql.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));

		SashForm sashForm = new SashForm(grpSql, SWT.NONE);

		tableParam = new Table(sashForm, SWT.BORDER | SWT.FULL_SELECTION);
		tableParam.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true,
				1, 1));
		tableParam.setLinesVisible(true);
		tableParam.addListener(SWT.MeasureItem, new Listener() {
			public void handleEvent(Event event) {
				event.height = 20;
			}
		});
		TableColumn tblclmnNewColumn_4 = new TableColumn(tableParam, SWT.NONE);
		tblclmnNewColumn_4.setWidth(25);
		tblclmnNewColumn_4.setText("New Column");
		TableColumn tblclmnNewColumn_5 = new TableColumn(tableParam, SWT.NONE);
		tblclmnNewColumn_5.setWidth(100);
		tblclmnNewColumn_5.setText("New Column");
		// ==========================================
		// 参数编辑
		// ===========================================
		final Composite paramEdit = new Composite(tableParam, SWT.NONE);
		GridLayoutFactory.create(paramEdit).columns(2).noSpacing().marginsH(4)
				.marginsV(0);

		textParamEdit = new Text(paramEdit, SWT.NONE);
		textParamEdit.setBackground(SWTResourceManager.getColor(232, 242, 254));
		GridDataFactory.create(textParamEdit).grabV().grabH().fillH();
		Button btnSelected = new Button(paramEdit, SWT.ARROW);
		btnSelected.setText("...");
		btnSelected.setToolTipText("选择参数值");
		btnSelected.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				doSetParamValue();
			}
		});
		paramEditor = new TableEditor(tableParam);
		paramEditor.grabHorizontal = true;
		paramEditor.grabVertical = true;
		paramEditor.setEditor(paramEdit);
		paramEdit.setBackground(textParamEdit.getBackground());

		Menu menu = new Menu(tableParam);
		tableParam.setMenu(menu);

		MenuItem mntmNewItem = new MenuItem(menu, SWT.NONE);
		mntmNewItem.setText("新增参数&N");
		mntmNewItem.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				doAddParam();
			}
		});

		MenuItem menuMoveUp = new MenuItem(menu, SWT.NONE);
		menuMoveUp.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				doMoveParam(-1);
			}
		});
		menuMoveUp.setText("上移");

		MenuItem menuMoveDown = new MenuItem(menu, SWT.NONE);
		menuMoveDown.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				doMoveParam(1);
			}
		});
		menuMoveDown.setText("下移");
		MenuItem mntmNewItem_1 = new MenuItem(menu, SWT.NONE);
		mntmNewItem_1.setText("移除参数&D");
		mntmNewItem_1.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				doRemoveParam();
			}
		});

		textSql = new CodeStyleText(sashForm, SWT.BORDER | SWT.V_SCROLL
				| SWT.MULTI);
		textSql.setFont(SWTResourceManager.getFont("Courier New", 10,
				SWT.NORMAL));

		Menu menu_2 = new Menu(textSql);
		textSql.setMenu(menu_2);

		MenuItem mntmNewItem_4 = new MenuItem(menu_2, SWT.NONE);
		mntmNewItem_4.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				buildParams();
			}
		});
		mntmNewItem_4.setText("生成参数&B");
		sashForm.setWeights(new int[] { 3, 7 });
		StyleRange range = new StyleRange();
		range.font = textSql.getFont();
		textSql.addRule(CodeStyleFactory.buildSqlRules(range));
		TabItem tbtmNewItem_2 = new TabItem(tabFolder, SWT.NONE);
		tbtmNewItem_2.setText("数据列");

		Composite composite_6 = new Composite(tabFolder, SWT.NONE);
		tbtmNewItem_2.setControl(composite_6);
		composite_6.setLayout(new GridLayout(1, false));

		tableDataColumn = new Table(composite_6, SWT.BORDER | SWT.CHECK
				| SWT.FULL_SELECTION);
		tableDataColumn.setLinesVisible(true);
		tableDataColumn.setHeaderVisible(true);
		tableDataColumn.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true,
				true, 1, 1));

		TableColumn tblclmnNewColumn_2 = new TableColumn(tableDataColumn,
				SWT.NONE);
		tblclmnNewColumn_2.setResizable(false);
		tblclmnNewColumn_2.setWidth(81);
		tblclmnNewColumn_2.setText("是否为主键");

		TableColumn tblclmnNewColumn_1 = new TableColumn(tableDataColumn,
				SWT.NONE);
		tblclmnNewColumn_1.setWidth(172);
		tblclmnNewColumn_1.setText("列名");

		TableColumn tblclmnNewColumn = new TableColumn(tableDataColumn,
				SWT.NONE);
		tblclmnNewColumn.setWidth(100);
		tblclmnNewColumn.setText("数据类型");

		TableColumn tblclmnNewColumn_3 = new TableColumn(tableDataColumn,
				SWT.NONE);
		tblclmnNewColumn_3.setWidth(100);
		tblclmnNewColumn_3.setText("长度");

		TableCursor tableCursor = new TableCursor(tableDataColumn, SWT.NONE);
		tableDataColumn.addListener(SWT.MeasureItem, new Listener() {
			public void handleEvent(Event event) {
				event.height = 20;
			}
		});
		// tableCursor.setBackground(SWTResourceManager.getColor(SWT.COLOR_BLUE));
		Label label = new Label(shell, SWT.SEPARATOR | SWT.HORIZONTAL);
		label.setLayoutData(new GridData(SWT.FILL, SWT.CENTER, true, false, 1,
				1));

		Composite composite_5 = new Composite(shell, SWT.NONE);
		RowLayout rl_composite_5 = new RowLayout(SWT.HORIZONTAL);
		rl_composite_5.pack = false;
		composite_5.setLayout(rl_composite_5);
		composite_5.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false,
				false, 1, 1));

		Button btnNewButton = new Button(composite_5, SWT.NONE);
		btnNewButton.setText("&P预览数据");
		btnNewButton.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				doPreview();
			}
		});
		Button btnNewButton_10 = new Button(composite_5, SWT.NONE);
		btnNewButton_10.setText("   &O确定   ");
		btnNewButton_10.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				okPressed();
			}
		});
		Button btnNewButton_9 = new Button(composite_5, SWT.NONE);
		btnNewButton_9.setText("&C取消");
		btnNewButton_9.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				cancel();
			}
		});
		initializeListener();
		initializeData();
	}

	// 移除参数
	protected void doRemoveParam() {
		if (tableParam.getSelectionCount() <= 0) {
			MessageDialog.openInformation(shell, "提示", "请选择需要移除的记录");
			return;
		}
		tableParam.getSelection()[0].dispose();
		if (tableParam.getSelectionCount() == 0) {
			paramEditor.getEditor().setVisible(false);
		}
	}

	// 预览数据
	protected void doPreview() {
		List list = new ArrayList();
		for (TableItem item : tableParam.getItems()) {
			Param param = (Param) item.getData(item.getText(1));
			if (param != null) {// 如果选择了控件绑定值 ，那么该参数将为null
				list.add(param.value);
			} else {
				list.add(item.getText(1));
			}
		}
		CachedRowSet set;
		try {
			set = IDataBaseProvideHelp.getRowSet(baseProvideClass,
					textSql.getText(), list.toArray());

		} catch (Exception e) {
			ExecutionUtils2.openErrorDialog("预览数据获取失败", e);
			return;
		}
		DatasetPreviewDialog dlg = new DatasetPreviewDialog(shell, set);
		dlg.open();
	}

	// 查找系统定义数据集
	protected void doSelectedDefine() {
		DatasetDefineDialog dlg = new DatasetDefineDialog(shell,
				baseProvideClass);
		if (dlg.open() == Window.OK) {
			sysdefine = dlg.define;
			setDefineText();// 设置数据集信息
			// 构建参数
			// tableParam.removeAll();
			// buildParams();
		}
	}

	// 调整参数顺序
	protected void doMoveParam(int amount) {
		int index = tableParam.getSelectionIndex();
		int index2 = index + amount;
		if (index2 >= 0 && index2 < tableParam.getItemCount()) {
			TableItem item1 = tableParam.getItem(index);
			TableItem item2 = tableParam.getItem(index2);
			String text1 = item1.getText(1);
			Object data1 = item1.getData(item1.getText(1));
			item1.setText(1, item2.getText(1));
			item1.setData(item2.getText(1), item2.getData(item2.getText(1)));
			item2.setText(1, text1);
			item2.setData(text1, data1);
			tableParam.setSelection(item2);
			activateParamEdit();
			textParamEdit.setFocus();
		}
	}

	private void initializeListener() {
		//
		btnSys.addSelectionListener(checkEnable);
		btnCustom.addSelectionListener(checkEnable);
		// 参数表界面样式
		tableParam.addListener(SWT.EraseItem, new Listener() {
			public void handleEvent(Event event) {
				Rectangle bounds = event.getBounds();
				if (event.index == 0) {
					Color oldBackground = event.gc.getBackground();
					if ((event.detail & SWT.SELECTED) == 0) {
						event.gc.setBackground(event.item.getDisplay()
								.getSystemColor(SWT.COLOR_GRAY));
					} else {
						event.gc.setBackground(event.item.getDisplay()
								.getSystemColor(SWT.COLOR_WIDGET_LIGHT_SHADOW));
					}
					event.gc.fillRectangle(bounds);
					event.gc.drawString(
							tableParam.indexOf((TableItem) event.item) + "",
							bounds.x + 4, bounds.y + 4);
					event.gc.setBackground(oldBackground);
				}

				// Rectangle r=new Rectangle(bounds.x-1, bounds.y-1,
				// bounds.width, bounds.height);
				// event.gc.drawRectangle(r);
				// if (event.index == 1)
				event.detail &= ~SWT.SELECTED;
			}
		});
		tableParam.addPaintListener(new PaintListener() {
			public void paintControl(PaintEvent e) {
				if (tableParam.getItemCount() <= 0)
					return;
				int width = 0;
				Rectangle bounds = tableParam.getItem(// 最后一行的位置
						tableParam.getItemCount() - 1).getBounds(0);
				int height = bounds.y + bounds.height;
				for (TableColumn c : tableParam.getColumns()) {
					width += c.getWidth();
					e.gc.drawLine(width, 0, width, height);
				}
				for (TableItem item : tableParam.getItems()) {
					Rectangle b = item.getBounds(0);
					e.gc.drawLine(0, b.y + b.height, width, b.y + b.height);
				}
				if (tableParam.getSelection().length > 0) {
					Color old = e.gc.getForeground();
					e.gc.setForeground(e.display.getSystemColor(SWT.COLOR_RED));
					Rectangle b = tableParam.getSelection()[0].getBounds(0);
					e.gc.drawLine(0, b.y + b.height, width, b.y + b.height);
					e.gc.setForeground(old);
				}
			}
		});
		textParamEdit.addModifyListener(new ModifyListener() {
			public void modifyText(ModifyEvent e) {
				if (paramEditor.getItem() != null)
					paramEditor.getItem().setText(1, textParamEdit.getText());
			}
		});
		tableParam.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				activateParamEdit();
				textParamEdit.setFocus();
			}
		});
		tableParam.addControlListener(new ControlAdapter() {
			@Override
			public void controlResized(ControlEvent e) {
				int width0 = tableParam.getColumn(0).getWidth();
				int width1 = tableParam.getSize().x;
				if (tableParam.getVerticalBar().isVisible()) {
					tableParam.getColumn(1).setWidth(width1 - width0 - 25);
				} else {
					tableParam.getColumn(1).setWidth(width1 - width0 - 5);
				}
			}
		});
		// 构建数据集列
		tabFolder.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				if (tabFolder.getSelectionIndex() == 1) {
					buildDataColumns();
				}
			}
		});
		// 修改主键列
		tableDataColumn.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				keyList.clear();
				for (TableItem item : tableDataColumn.getItems()) {
					if (item.getChecked()) {
						keyList.add(item.getText(1));
					}
				}
			}
		});
		Listener textSqlListener = new Listener() {
			public void handleEvent(Event e) {
				textSql.setToolTipText("");
				// 显示设置的指针 cursor
				int offset = -1;
				try {
					offset = textSql.getOffsetAtLocation(new Point(e.x, +e.y));
				} catch (Exception e1) {
					return;
				}
				if (offset < 0 || offset >= textSql.getCharCount()) {
					return;
				}
				StyleRange range = textSql.getStyleRangeAtOffset(offset);
				if (range == null) {
					return;
				}
				List<StyleRange> ranges = textSql
						.getStyleRangeByRule("placeSign");
				int index = -1;
				for (StyleRange r : ranges) {
					if (r.start == range.start && r.length == range.length) {
						index = ranges.indexOf(r);
						break;
					}
				}
				if (index < 0 || index >= tableParam.getItemCount()) {
					return;
				}
				TableItem item = tableParam.getItem(index);
				if (e.type == SWT.MouseHover) {
					String tipText = "参数序号：" + index + "\r\n参 数 值："
							+ item.getText(1);
					textSql.setToolTipText(tipText);
				}
				if (e.type == SWT.MouseDown) {
					tableParam.setSelection(item);
					activateParamEdit();
				}
			}
		};
		textSql.addListener(SWT.MouseHover, textSqlListener);
		textSql.addListener(SWT.MouseDown, textSqlListener);
	}

	/*
	 * 激活当前选中参数 编辑
	 */
	private void activateParamEdit() {
		// 打开参数编辑器
		TableItem item = tableParam.getSelection()[0];
		paramEditor.setEditor(textParamEdit.getParent(), item, 1);
		textParamEdit.setText(item.getText(1));
		textParamEdit.selectAll();
		tableParam.update();

		// 定位指定参数的占位符'?'
		List<StyleRange> ranges = textSql.getStyleRangeByRule("placeSign");
		int index = tableParam.getSelectionIndex();
		if (index < ranges.size()) {
			StyleRange range = ranges.get(index);
			textSql.setSelection(range.start, range.start + range.length);
		}
	}

	private void initializeData() {

		if (dataset != null) {
			baseProvideClass = dataset.getProvideClass();
			isSysSource = dataset.isSysSource();
			defineKey = dataset.getDefineKey();
			sqlCommand = dataset.getSqlCommand();
			shell.setImage(ObjectsLabelProvider.INSTANCE.getImage(dataset));
			String[] keys = dataset.getDataKeyColumns();
			keyList.clear();
			keys = keys == null ? new String[0] : keys;
			for (String k : keys) {
				keyList.add(k);
			}
		}
		// 获取加载方试
		if (dataset.getMethodInvocation("update()") != null) {
			MethodDeclaration method = AstNodeUtils.getEnclosingMethod(dataset
					.getMethodInvocation("update()"));
			String sign = AstNodeUtils.getMethodSignature(method);
			if (sign.equals("createGUIBefore()")) {
				loadType = 2;
			} else if (sign.equals("createGUIAfter()")) {
				loadType = 3;
			}
		}
		btnLoadType0.setSelection(loadType == 0);
		btnLoadType1.setSelection(loadType == 1);
		btnLoadType2.setSelection(loadType == 2);
		btnLoadType3.setSelection(loadType == 3);
		textSql.setText(toString(sqlCommand));
		if (baseProvideClass != null) {
			try {
				baseProvideClass = IDataBaseProvideHelp
						.loadProvideClass(baseProvideClass.getName());
			} catch (Exception e) {
				DesignerPlugin.log(e);
				ExecutionUtils2.openErrorDialog("解析器加载失败", e);
				baseProvideClass = null;
			}
		} else {
			try {
				baseProvideClass = IDataBaseProvideHelp
						.getDefaultProvideClass();
			} catch (Exception e) {
				ExecutionUtils2.openErrorDialog("加载默认解析器失败", e);
			}
		}
		combSourceProvide.removeAll();
		for (String s : IDataBaseProvideHelp.getProvideClassByCache()) {
			combSourceProvide.add(s);
		}
		if (baseProvideClass != null) {
			combSourceProvide.setText(baseProvideClass.getName());
		}

		btnCustom.setSelection(!isSysSource);
		btnSys.setSelection(isSysSource);
		checkEnable.widgetSelected(null);
		if (defineKey != null) {
			try {
				sysdefine = IDataBaseProvideHelp.getDatasetDefine(
						baseProvideClass, defineKey);
				if (sysdefine == null) {
					throw new RuntimeException("数据集不存在");
				}
				setDefineText();
			} catch (Exception e) {
				ExecutionUtils2.openErrorDialog(
						"加载数据集'" + defineKey + "'信息失败:", e);
			}
		}

		// ======================
		// 初始化column
		// ======================
		buildDataColumns();
		// if (!dataset.isInstantiationData()) {
		// ExecutionUtils2.runErrorDlg("数据更新出现异常", new RunnableEx() {
		// public void run() throws Exception {
		// dataset.updateData();
		// }
		// });
		// }
		// try {
		// String[] columns = dataset.getDataColumns();
		//
		// TableItem item;
		// for (String c : columns) {
		// item = new TableItem(tableDataColumn, SWT.NONE);
		// item.setText(0, "否");
		// // 是否为主键列
		// for (String k : keyList) {
		// if (c.equalsIgnoreCase(k)) {
		// item.setText(0, "是");
		// item.setChecked(true);
		// break;
		// }
		// }
		// item.setText(1, toString(c));
		// item.setText(2, dataset.getDataType(c).getSimpleName());
		// }
		// } catch (Exception e) {
		// ExecutionUtils2.openErrorDialog("未能获得数据集列", e);
		// }
		// ======================
		// 初始化参数信息
		// ======================
		String signature = ReflectionUtils.getMethodSignature("setParam",
				new Class[] { int.class, Object.class });
		List<MethodInvocation> setParams = dataset
				.getMethodInvocations(signature);
		// TypeDeclaration declaration =
		// JavaInfoUtils.getTypeDeclaration(dataset
		// .getRootJava());
		// MethodDeclaration setParamMethod = AstNodeUtils.getMethodBySignature(
		// declaration, "setParams(java.lang.Object)");
		// List<Statement> statements = DomGenerics.statements(setParamMethod
		// .getBody());
		// for (Statement s : statements) {
		// System.out.println(s);
		// }
		for (MethodInvocation i : setParams) {
			int index = (Integer) JavaInfoEvaluationHelper
					.getValue((Expression) i.arguments().get(0));// 获取参数1
			Object param2 = i.arguments().get(1); // 获取参数2

			String source;
			JavaInfo info;
			Param param = null;
			if (param2 instanceof MethodInvocation) {
				info = dataset.getRootJava().getChildRepresentedBy(
						((MethodInvocation) param2).getExpression());
				if (info != null) {
					param = new Param();
					param.target = info;
					String mp = param2.toString();
					param.signature = mp.substring(mp.indexOf(".") + 1);
					// AstNodeUtils
					// .getMethodSignature((MethodInvocation) param2);
				}
				source = param2.toString();
			} else {
				Object value = JavaInfoEvaluationHelper
						.getValue((Expression) param2);
				source = String.valueOf(value);
			}
			while (tableParam.getItemCount() <= index) {
				final TableItem item = new TableItem(tableParam, SWT.NONE);
				// item.setText(tableParam.indexOf(item) + "");
			}
			TableItem item = tableParam.getItem(index);
			item.setText(1, source);
			if (param != null) {
				item.setData(item.getText(1), param);
				// if (param.target != null)
				// item.setImage(1, ObjectsLabelProvider.INSTANCE
				// .getImage(param.target));
			}
		}

	}

	// 根据构sql语句生成参数项
	protected void buildParams() {
		if (baseProvideClass == null) {
			MessageDialog.openInformation(shell, "提示", "生成参数项失败，未指定解析器");
			return;
		} else if (textSql.getText().trim().equals("")) {
			MessageDialog.openInformation(shell, "提示", "生成参数项失败，SQL语句为空");
			return;
		}
		if (tableParam.getItemCount() > 0
				&& !MessageDialog.openQuestion(shell, "提示", "将会覆盖已设置的参数，是否继续?")) {
			return;
		}
		try {
			int paramCount = IDataBaseProvideHelp.getParamCount(
					baseProvideClass, textSql.getText());
			tableParam.removeAll();
			for (int i = 0; i < paramCount; i++) {
				new TableItem(tableParam, SWT.NONE);
			}
			paramEditor.getEditor().setVisible(false);
		} catch (Exception e) {
			ExecutionUtils2.openErrorDialog("生成参数失败", e);
		}
	}

	/*
	 * 构建数据集列
	 */
	protected void buildDataColumns() {
		if (baseProvideClass == null) {
			MessageDialog.openError(shell, "构建列错误", "未指定数据集解析器");
			return;
		} else if (textSql.getText().trim().equals("")) {
			MessageDialog.openError(shell, "构建列错误", "SQL语句为空");
			return;
		}
		tableDataColumn.removeAll();
		String[] columns = new String[0];
		Class<?>[] types = new Class[0];
		try {
			ResultSetMetaData metda = IDataBaseProvideHelp.getSetMetaData(
					baseProvideClass, textSql.getText());
			columns = new String[metda.getColumnCount()];
			types = new Class[metda.getColumnCount()];
			for (int i = 0; i < columns.length; i++) {
				columns[i] = metda.getColumnLabel(i + 1);
				types[i] = Class.forName(metda.getColumnClassName(i + 1));
			}
		} catch (Exception e) {
			ExecutionUtils2.openErrorDialog("未能获得数据集列", e);
			return;
		}
		TableItem item;
		for (int i = 0; i < columns.length; i++) {
			item = new TableItem(tableDataColumn, SWT.NONE);
			item.setText(0, "否");
			// 是否为主键列
			for (String k : keyList) {
				if (columns[i].equalsIgnoreCase(k)) {
					item.setText(0, "是");
					item.setChecked(true);
					break;
				}
			}
			item.setText(1, columns[i]);
			item.setText(2, types[i].getSimpleName());
		}
	}

	// 添加参数
	protected TableItem doAddParam() {
		final TableItem item = new TableItem(tableParam, SWT.NONE);
		// item.setText(tableParam.indexOf(item) + "");
		tableParam.setSelection(item);
		activateParamEdit();
		textParamEdit.setFocus();
		return item;
	}

	// 查找数据源提供器
	@SuppressWarnings("restriction")
	protected void doSearchSourceProvide() {
		try {
			String className = JdtUiUtils.selectTypeName(shell, dataset
					.getEditor().getJavaProject());
			if (className == null || className.trim().equals(""))
				return;
			baseProvideClass = IDataBaseProvideHelp.loadProvideClass(className);
			combSourceProvide.removeAll();
			for (String s : IDataBaseProvideHelp.getProvideClassByCache()) {
				combSourceProvide.add(s);
			}
			combSourceProvide.setText(className);
		} catch (Exception e) {
			DesignerPlugin.log(e);
			ExecutionUtils2.openErrorDialog("解析器加载失败", e);
		}
	}

	// 设置参数值
	protected void doSetParamValue() {
		ParamDialog dlg = new ParamDialog(shell, dataset.getRootJava());
		TableItem item = tableParam.getSelection()[0];
		Param param = (Param) item.getData(item.getText(1));
		dlg.param = param;
		if (dlg.open() == Window.OK) {
			param = dlg.param;
			String var = "";
			if (param.target != null) {
				var = param.target.getVariableSupport().getName();
				// item.setImage(1,
				// ObjectsLabelProvider.INSTANCE.getImage(param.target));
			}
			item.setText(1, var + "." + param.signature);
			textParamEdit.setText(item.getText(1));
			item.setData(item.getText(1), param);
			textParamEdit.setFocus();
			textParamEdit.selectAll();
			tableParam.update();
		}
	}

	protected void cancel() {
		result = CANCEL;
		shell.close();
	}

	protected void okPressed() {
		if (valdate()) {
			sqlCommand = textSql.getText();
			defineKey = (String) textDefineKey.getData();
			isSysSource = textDefineKey.getEnabled();
			for (TableItem item : tableParam.getItems()) {
				Object param = item.getData(item.getText(1));
				params.put(tableParam.indexOf(item), param != null ? param
						: item.getText(1));
			}
			keyList.clear();
			for (TableItem item : tableDataColumn.getItems()) {
				if (item.getChecked()) {
					keyList.add(item.getText(1));
				}
			}
			// 加载方式
			loadType = btnLoadType0.getSelection() ? 0 : loadType;
			loadType = btnLoadType1.getSelection() ? 1 : loadType;
			loadType = btnLoadType2.getSelection() ? 2 : loadType;
			loadType = btnLoadType3.getSelection() ? 3 : loadType;

			result = OK;
			shell.close();
		}
	}

	private boolean valdate() {
		boolean result = true;
		if (baseProvideClass == null) {
			MessageDialog.openWarning(shell, "提示信息", "必须选择数据源提供器");
			combSourceProvide.setFocus();
			result = false;
		}
		return result;
	}

	private void setDefineText() {
		if (sysdefine != null) {
			String cmd = ReflectionUtils.getFieldString(sysdefine, "command");
			String name = ReflectionUtils.getFieldString(sysdefine, "name");
			String id = ReflectionUtils.getFieldString(sysdefine, "id");
			textSql.setText(cmd == null ? "" : cmd);
			textDefineKey.setText(name + "(" + id + ")");
			textDefineKey.setData(id);
		} else {
			textSql.setText("");
			textDefineKey.setText("");
			textDefineKey.setData(null);
		}
	}

	private String toString(Object obj) {
		if (obj instanceof String) {
			return (String) obj;
		}
		return "";
	}
}
